package com.gsafety.wellsfort.common.util;

import com.alibaba.fastjson.JSON;
import com.gsafety.wellsfort.service.task.Task;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;

/**
 * 延迟队列封装
 *
 * @author tangjiawei
 * @date 2020/05/23
 */
@Slf4j
public class DelayQueueProvider {
    /**
     * 延迟队列
     */
    private static DelayQueue<Task> delayQueue;

    static {
        if (delayQueue == null) {
            synchronized (DelayQueueProvider.class) {
                if (delayQueue == null) {
                    delayQueue = new DelayQueue<Task>();
                }
            }
        }
    }

    /**
     * 添加任务
     *
     * @param task
     */
    public static void put(Task task) {
        log.info("延迟队列,存入任务task={}", JSON.toJSONString(task));
        delayQueue.put(task);
    }

    /**
     * 获取任务
     *
     * @return
     */
    public static Task get() {
        try {
            Task task = delayQueue.take();
            log.info("延迟队列,消费任务task={}", JSON.toJSONString(task));
            return task;
        } catch (InterruptedException e) {
            log.error("exception={}", e);
        }
        return null;
    }
}
